package com.gateway.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gateway.exceptions.IllegalTokenException;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mis_wu
 * @date 2021/12/5 13:34
 * 网关异常处理
 * order 按照数字自然排序执行1 4 7 -1代表优先在所有exception之前执行,filer中也可使用
 */
@Order(-1)
@Configuration
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {

    /**
     * 日志对象
     */
    public static final Logger log= LoggerFactory.getLogger(GlobalExceptionConfiguration.class);

    /**
     * 参数一：交换机  参数二：异常出现时的对象
     * @param exchange the current exchange
     * @param ex the exception to handle
     * @return
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        Map result=new HashMap(8);
        //1、获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //2、response是否结束 多个异常处理的时候
        if (response.isCommitted()){
            return Mono.error(ex);
        }

        //3、设置响应头类型 response.setContentType("application/json");
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        //4、设置响应状态码
        if (ex instanceof IllegalTokenException){
            //403
            response.setStatusCode(HttpStatus.FORBIDDEN);
        }else {
            //500
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }

        //5、设置响应内容
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            result.put("msg",ex.getMessage());
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }));
    }
}
